package cn.topcodes.tcsf.cms.service;

import cn.topcodes.tcsf.admin.commons.generic.GenericService;
import cn.topcodes.tcsf.cms.domain.entity.AlbumPicture;
import cn.topcodes.tcsf.cms.mapper.AlbumPictureMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * AlbumPicture 服务
 *
 * @author Yvan
 * @date 2018-02-09 10:46:26
 */
@Service
public class AlbumPictureService extends GenericService<AlbumPicture> {

    @Autowired
    private AlbumPictureMapper albumPictureMapper;

    /**
     * 保存圖冊照片
     *
     * @param id         图册ID
     * @param contentImg 图片url
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public void createOrUpdate(Long id, String contentImg) {
        if (StringUtils.isNotBlank(contentImg)) {
            String[] split = contentImg.split(",");
            for (String s : split) {
                if (StringUtils.isNotBlank(s)) {
                    Example example = this.buildExample();
                    example.or().andEqualTo(AlbumPicture.FIELD_ALBUMID, id)
                            .andEqualTo(AlbumPicture.FIELD_URL, s);
                    boolean exist = this.exist(example);
                    if (!exist) {
                        AlbumPicture albumPicture = new AlbumPicture();
                        albumPicture.setAlbumId(id);
                        albumPicture.setUrl(s);
                        Long maxSort = albumPictureMapper.findMaxSort(id);
                        albumPicture.setSort(maxSort == null ? 0 : ++maxSort);
                        this.create(albumPicture);
                    }
                }
            }
        }
    }
}
